package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver = null;

    public WebDriverWait wait = null;

    //详情页url
    public static String detailUrl = "http://8.137.19.140:9090/blog_detail.html?blogId=158477";
    public Utils(String url){
        driver = createDriver();
        //调用driver
        driver.get(url);
        //创建显式等待
        wait = new WebDriverWait(driver,Duration.ofSeconds(10));
    }

    //创建驱动对象
    public static WebDriver createDriver(){
        if (driver == null){
            //下载驱动
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //添加配置，允许访问所有的连接
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver = new ChromeDriver(options);
            //添加隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        }

        return driver;
    }


    //生成屏幕截图
    //./src/test/java/images/
    //                      /2025-11-07/
    //                                  /test01-15083020.png
    //                                  /test02-15083020.png
    //                      /2025-11-08/
    //                                  /test01-15083020.png
    //                                  /test02-15083020.png
    public void ScreenShot(String str) throws IOException {
        //年月日
        SimpleDateFormat sim1  = new SimpleDateFormat("yyyy-MM-dd");
        //时分秒毫秒
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //文件名： ./src/test/java/images/2025-11-07/test01-15083020.png
        String filename = "./src/test/java/images/" + dirTime + "/" + str + "-" + fileTime + ".png";

        File srcfile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcfile,new File(filename));
    }
}


















